import os
# from PIL import Image
import numpy as np
from os import path
from random import randint, choice

import matplotlib.pyplot as plt
from PIL import Image
from wordcloud import WordCloud, ImageColorGenerator
from data import mylearn


def random_color_func(word=None, font_size=None, position=None, orientation=None, font_path=None, random_state=None):
    h = choice([randint(0, 99), randint(155, 180)])
    s = int(100.0 * 255.0 / 255.0)
    l = int(100.0 * float(randint(80, 160)) / 255.0)
    return "hsl({}, {}%, {}%)".format(h, s, l)


def pm2px(d):
    return round(d * 96 / 25.4)


d = path.dirname(__file__) if "__file__" in locals() else os.getcwd()
font_path = d + '/MSYH.TTC'
mask_path = d + '/bmask14.png'

b_mask = np.array(Image.open(mask_path))
image_colors = ImageColorGenerator(b_mask)
# wordcloud = WordCloud(width=pm2px(74.69 * 3), height=pm2px(157.89 * 3), margin=5, font_path=font_path,
#                       color_func=random_color_func, mask=b_mask).fit_words(dict(mylearn))

wordcloud = WordCloud(margin=5, font_path=font_path,
                      color_func=random_color_func, mask=b_mask).fit_words(dict(mylearn))

plt.imshow(wordcloud, interpolation="bilinear")

fig = plt.gcf()
height, width, channels = b_mask.shape
fig.set_size_inches(width/100.0/3.0, height/100.0/3.0)
plt.gca().xaxis.set_major_locator(plt.NullLocator())
plt.gca().yaxis.set_major_locator(plt.NullLocator())
plt.subplots_adjust(top=1, bottom=0, right=1, left=0, hspace=0, wspace=0)
plt.margins(0, 0)
fig.savefig('test.png', format='png', transparent=True, dpi=300, pad_inches=0)

# plt.savefig('test.png', dpi=1024)
plt.axis("off")
plt.show()
# wordcloud.to_file('test.png')
